﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shop.Order.Models;
using System.IO;
using Shop.Core.Common;
using System.Text.RegularExpressions;
using System.Collections;
using PetaPoco;

namespace Shop.Order.Controllers
{
    public class OrderController : Controller
    {
        Shop.Order.Services.OrderAccess bll = new Services.OrderAccess();
        Shop.Order.Services.CourierAccess cbll = new Services.CourierAccess();
        #region 订单管理
        /// <summary>
        /// 订单管理界面
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderManage()
        {
            return View();
        }
        /// <summary>
        /// 订单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult _OrderSearch(int Page)
        {
            PetaPoco.Page<Models.Order> oinfo = bll.GetOInfo(Page, 5, 2, 9, "", "", 1, "", 0);
            return View(oinfo);
        }
        [HttpPost]
        public ActionResult _OrderSearch()
        {
            //第几页
            int Page;
            int.TryParse(Request.Form["Page"],out Page);
            //每页多少行
            int PageNum;
            int.TryParse(Request.Form["PageNum"], out PageNum);
            //支付状态
            int IfPay;
            int.TryParse(Request.Form["IfPay"], out IfPay);
            //订单状态
            int Status;
            int.TryParse(Request.Form["Status"], out Status);
            //搜索类型
            int SearchType;
            int.TryParse(Request.Form["SearchType"], out SearchType);
            //排序方式
            int order;
            int.TryParse(Request.Form["order"], out order);
            //搜索内容
            string Search = Request.Form["Search"];
            //开始时间
            string Start = Request.Form["Start"];
            //结束时间
            string End = Request.Form["End"];
            Page = Page <= 0 ? 1 : Page;
            PetaPoco.Page<Models.Order> oinfo = bll.GetOInfo(Page, PageNum, IfPay, Status, Start, End, SearchType, Search, order);
            return View(oinfo);
        }
        /// <summary>
        /// 订单详情分布页
        /// </summary>
        /// <param name="OrderNumber"></param>
        /// <returns></returns>
        public ActionResult _OrderDetail(string OrderNumber)
        {
            //根据订单号获取订单详情信息
            IList<AnyOrderDetail> ODInfo = bll.GetUserODInfo(OrderNumber);
            //根据订单号获取订单信息
            Models.Order OInfo = bll.GetOInfoByOrderNumber(OrderNumber);
            ViewBag.OInfo = OInfo;
            return View(ODInfo);
        }
        /// <summary>
        /// 要发货的订单的信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DeliveryInfo()
        {
            string OrderNumber = Request.Form["OrderNumber"];
            IList<AnyOrderDetail> ODInfo = bll.GetUserODInfo(OrderNumber);
            return Json(ODInfo, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult VCourierCategory()
        {
            string CCode = Request.Form["CCode"];
            if (cbll.VCourierCategory(CCode) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }

        public ActionResult Delivery()
        {
            string CCode = Request.Form["CCode"];
           
            Courier cinfo = cbll.GetCurier(CCode);
            
            string OrderNumber = Request.Form["OrderNumber"];
            if (bll.Delivery(OrderNumber,cinfo.CourierNumber,cinfo.CCode) == 0)
            {
                return Content("NO");
            }

            if (cbll.UseCourier(cinfo.CourierNumber)==0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        [HttpPost]
        public ActionResult ExportOrder()
        {
            Response.BufferOutput = false;
            Response.ContentEncoding = System.Text.Encoding.Default;
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("content-disposition", "attachment;filename=订单.csv;");
            //第几页
            int Page;
            int.TryParse(Request.Form["Page"], out Page);
            //每页多少行
            int PageNum;
            int.TryParse(Request.Form["PageNum"], out PageNum);
            //支付状态
            int IfPay;
            int.TryParse(Request.Form["IfPay"], out IfPay);
            //订单状态
            int Status;
            int.TryParse(Request.Form["Status"], out Status);
            //搜索类型
            int SearchType;
            int.TryParse(Request.Form["SearchType"], out SearchType);
            //排序方式
            int order;
            int.TryParse(Request.Form["order"], out order);
            //搜索内容
            string Search = Request.Form["Search"];
            //开始时间
            string Start = Request.Form["Start"];
            //结束时间
            string End = Request.Form["End"];
            Page = Page <= 0 ? 1 : Page;
            Response.Write("商品编号,商品名,收货人姓名,收货人地址,收货人电话" + Environment.NewLine);
            Page<Models.Order> oinfo = bll.GetOInfo(Page, PageNum, IfPay, Status, Start, End, SearchType, Search, order);
            for (int i = 0; i < oinfo.Items.Count; i++)
            {
                //根据订单号获取订单详情信息
                IList<AnyOrderDetail> ODInfo = bll
                    .GetUserODInfo(oinfo.Items[i].OrderNumber);
                for (int s = 0; s < ODInfo.Count; s++)
                {
                    string str = string.Format("{0},{1},{2},{3},{4}"
                        , ODInfo[s].WID, ODInfo[s].WName, 
                        oinfo.Items[i].UName, oinfo.Items[i].Address
                        , oinfo.Items[i].Tel);
                    Response.Write(str + Environment.NewLine);
                }
            }
            Response.End();
            return View();
        }
        #endregion

        #region 基础管理
        public ActionResult CourierCategory()
        {
            IList<Models.CourierCategory> ccinfo = cbll.GetCCInfo();
            return View(ccinfo);
        }

        [HttpPost]
        public ActionResult AddCourierCategory()
        {
            string CName = Request.Form["CName"];
            string CLength = Request.Form["CLength"];
            CourierCategory cinfo = new Models.CourierCategory();
            cinfo.CName = CName;
            cinfo.CReg = CLength;
            cinfo.CreateDate = DateTime.Now;
            cbll.AddCourierCategory(cinfo);
            try
            {

                return Content("OK");
            }
            catch (Exception)
            {
                return Content("NO");
            }

        }

        [HttpPost]
        public ActionResult UpdateCourierCategory()
        {
            int CCID = Convert.ToInt32(Request.Form["CCID"]);
            string CName = Request.Form["CName"];
            string CLength = Request.Form["UCLength"];
            DateTime CreateDate = Convert.ToDateTime(Request.Form["CreateDate"]);
            CourierCategory cinfo = new CourierCategory();
            cinfo.CCID = CCID;
            cinfo.CName = CName;
            cinfo.CReg = CLength;
            cinfo.CreateDate = CreateDate;
            try
            {
                cbll.UpdateCourierCategory(cinfo);
                return Content("OK");
            }
            catch (Exception)
            {
                return Content("NO");
            }
        }

        [HttpPost]
        public ActionResult DelCourierCategory()
        {
            int CCID = Convert.ToInt32(Request.Form["CCID"]);

            if (cbll.GetCCount(CCID) > 0)
            {
                return Content("NO2");
            }
            if (cbll.DelCourierCategory(CCID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }


        [HttpPost]
        public ActionResult VerificationCName()
        {
            string CName = Request.Form["CName"];
            if (cbll.VerificationCName(CName) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }

        [HttpPost]
        public ActionResult UVerificationCName()
        {
            string CName = Request.Form["CName"];
            string YCName = Request.Form["YCName"];
            if (cbll.UVerificationCName(CName, YCName) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }



        public ActionResult CourierManage()
        {
            return View();
        }

        public ActionResult _CourierSearch()
        {
            Page<Models.AnyCourier> cinfo = cbll.GetCinfo(1, 5, 9, "", "", 0, "", 0, "9");
            return View(cinfo);
        }

        [HttpPost]
        public ActionResult Post_CourierSearch()
        {
            int Page;
            int.TryParse(Request.Form["Page"], out Page);
            int PageNum;
            int.TryParse(Request.Form["PageNum"], out PageNum);
            int Status;
            int.TryParse(Request.Form["Status"], out Status);
            int SearchType;
            int.TryParse(Request.Form["SearchType"], out SearchType);
            int order;
            int.TryParse(Request.Form["order"], out order);

            string Start = Request.Form["Start"];
            string End = Request.Form["End"];
            string Search = Request.Form["Search"];
            string CCode = Request.Form["CCode"];

            Page = Page <= 0 ? 1 : Page;


            Page<Models.AnyCourier> cinfo = cbll.GetCinfo(Page, PageNum, Status, Start, End, SearchType, Search, order, CCode);
            return View("_CourierSearch", cinfo);
        }

        public ActionResult _CCode()
        {
            IList<CourierCategory> ccinfo = cbll.GetCCInfo();
            return View(ccinfo);
        }

        [HttpPost]
        public ActionResult DelCourier()
        {
            int CID;
            int.TryParse(Request.Form["CID"], out CID);
            if (cbll.DelCourier(CID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }

        public ActionResult AddCourier()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [HandleError(View = "~/Views/Shared/Error.cshtml")]
        public ActionResult Browse(HttpPostedFileBase file)
        {
            if (string.Empty.Equals(file.FileName) || ".xlsx" != Path.GetExtension(file.FileName))
            {
                throw new ArgumentException("当前文件格式不正确,请确保正确的Excel文件格式!");
            }
            var severPath = this.Server.MapPath("/files/"); //获取当前虚拟文件路径
            var savePath = Path.Combine(severPath, file.FileName); //拼接保存文件路径
            try
            {
                file.SaveAs(savePath);
                IList<Courier> stus = ExcelHelper.ReadExcelToEntityList<Courier>(savePath);
                List<Courier> estus = new List<Courier>();
                Hashtable ht = new Hashtable();
                for (int i = 0; i < stus.Count; i++)
                {
                    if (ht.Contains(stus[i].CourierNumber))
                    {
                        ViewBag.PanDuan = 2;
                        ViewBag.DanHao = stus[i].CourierNumber;
                        return View("AddCourier");
                    }
                    else
                    {
                        ht.Add(stus[i].CourierNumber, stus[i].CourierNumber);
                    }
                }
                for (int i = 0; i < stus.Count; i++)
                {
                    CourierCategory ccinfo = cbll.GetCCInfo(stus[i].CCode);
                    if (ccinfo != null)
                    {
                        //如果格式不正确就放入错误的集合中
                        Regex r = new Regex(ccinfo.CReg);
                        if (!r.IsMatch(stus[i].CourierNumber))
                        {
                            estus.Add(stus[i]);
                        }

                        if (cbll.GetCInfo(stus[i].CourierNumber) != null)
                        {
                            estus.Add(stus[i]);
                        }
                    }

                    else
                    {
                        estus.Add(stus[i]);
                    }
                }
                if (estus.Count > 0)
                {
                    ViewBag.PanDuan = 0;
                    ViewBag.Data = estus;
                    return View("AddCourier");
                }
                else
                {
                    ViewBag.PanDuan = 1;
                    ViewBag.Data = stus;
                    ViewBag.VCourier = DateTime.Now.Ticks.ToString();
                    Session["Courier"] = stus;
                    Session["VCourier"] = ViewBag.VCourier;
                    return View("AddCourier");
                }
            }
            catch (Exception)
            {
                return Content("内容格式不正确，请确认后再上传");
            }
            finally
            {
                System.IO.File.Delete(savePath);//每次上传完毕删除文件
            }
        }

        [HttpPost]
        public ActionResult AddCourier(FormCollection FC)
        {
            string VCourier = Request.Form["VCourier"];
            string VCouriers = Session["VCourier"].ToString();
            if (string.IsNullOrEmpty(VCouriers))
            {
                var scripts = ("<script>alert('添加超时');document.location.href = 'AddCourier'; </script>");
                return Content(scripts);
            }
            if (VCourier != VCouriers)
            {
                var scripts = ("<script>alert('添加超时');document.location.href = 'AddCourier'; </script>");
                return Content(scripts);
            }
            IList<Courier> cinfo = (IList<Courier>)Session["Courier"];
            if (cinfo == null)
            {
                var scripts = ("<script>alert('添加超时');document.location.href = 'AddCourier'; </script>");
                return Content(scripts);
            }


            for (int i = 0; i < cinfo.Count; i++)
            {
                cinfo[i].Status = 0;
                cinfo[i].CreateDate = DateTime.Now;
                try
                {
                    cbll.AddCourier(cinfo[i]);
                }
                catch (Exception)
                {
                    var scripts = ("<script>alert('添加过程中出现错误。。。');document.location.href = 'AddCourier'; </script>");
                    return Content(scripts);
                }
            }
            return Content("<script>alert('添加成功');document.location.href = 'AddCourier'; </script>");
        } 
        #endregion


    }
}